﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Net;
using XingFuStudio.Pioneer.Entity;
using XingFuStudio.Pioneer.Applications.City.Entity;
using XingFuStudio.Pioneer.Applications.City.Config;
using XingFuStudio.Pioneer.IO;
using FluorineFx.IO;
using XingFuStudio.Pioneer.Applications.City.Config.ConfigKeys;

namespace XingFuStudio.Pioneer.Applications.City.Operation {
    /// <summary>
    /// 火车相关操作
    /// </summary>
    public class Train  : OPBase{
        /// <summary>
        /// 调用方法的目标类
        /// </summary>
        private readonly string Target = "CCityTrain.callfunc";

        /// <summary>
        /// 创建业务对象
        /// </summary>
        /// <param name="httpManager"></param>
        /// <param name="account"></param>
        /// <param name="city"></param>
        /// <param name="config"></param>
        public Train(HttpManager httpManager, AccountInfo account, CityInfo city, UserConfigSection config)
            : base(httpManager, account, city, config) {
        }

        /// <summary>
        /// 重写操作方法
        /// </summary>
        public override void Operate() {
            base.Operate();

            //初始化值为Null
            object value = null;
            //初始化字典是否有值标识
            bool hasValue = false;

            string message = String.Empty;
           
            try {
                //判断城市是否有车站
                if (city.MyTrainStatus != ProductStatus.None) {
                    foreach (TrainInfo train in city.Trains) {
                        if (train.TrainOwner == null) {
                            //判断是否有值，并获取是否自动完成交易属性
                            hasValue = config.ConfigItems.TryGetValue(TrainConfigKeys.AutoDeal, out value);
                            if (hasValue && Convert.ToBoolean(value)) {
                                //完成交易
                                bool result = this.Deal(train.OId, out message);
                                //打印日志
                                this.DoPrintLog(true, message);

                                if (result) {
                                    city.MyTrainStatus = ProductStatus.Waiting;
                                }
                            }
                        } else {
                            //判断是否有值，并获取是否自动接受好友请求属性
                            hasValue = config.ConfigItems.TryGetValue(TrainConfigKeys.AutoAccept, out value);
                            if (hasValue && Convert.ToBoolean(value)) {
                                //接受好友请求
                                bool result = this.Accept(train, out message);
                                //打印日志
                                this.DoPrintLog(true, message);
                            }
                        }
                    }

                    //判断是否有值，并获取是否自动开始交易属性值
                    hasValue = config.ConfigItems.TryGetValue(TrainConfigKeys.AutoSendOut, out value);
                    if (hasValue && Convert.ToBoolean(value)) {
                        if (city.MyTrainStatus == ProductStatus.Waiting) {
                            //判断是否有值，并获取自动交易定单ID属性值
                            hasValue = config.ConfigItems.TryGetValue(TrainConfigKeys.SendOutOrderId, out value);
                            if (hasValue) {
                                //开始交易
                                bool result = this.SendOut(Convert.ToInt32(value), out message);
                                //打印日志
                                this.DoPrintLog(true, message);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                this.DoError(ex);
            }
        }

        /// <summary>
        /// 出行
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public bool SendOut(int pid, out string resultMessage) {
            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "sendout", pid);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data = (Dictionary<string, object>)content["data"];

            //获取数据是否成功的状态
            bool result = (string)data["result"] == "succ";
            resultMessage = ((string)data["msg"]).NoHtml();

            return result;
        }

        /// <summary>
        /// 自己车进站
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public bool Deal(int pid, out string resultMessage) {
            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "deal", pid);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data = (Dictionary<string, object>)content["data"];

            //获取数据是否成功的状态
            bool result = (string)data["result"] == "succ";
            if (result) {
                resultMessage = "火车进站成功";

                Dictionary<string, object> change = (Dictionary<string, object>)data["change"];

                object strTemp = null;
                bool has = change.TryGetValue("goods", out strTemp);
                if (has) {
                    resultMessage = String.Format("火车进站成功, 货物增加{0}", Convert.ToInt32(strTemp));
                }
                has = change.TryGetValue("cash", out strTemp);
                if (has) {
                    resultMessage = String.Format("火车进站成功, 现金增加{0}", Convert.ToInt32(strTemp));
                }
            } else {
                resultMessage = "火车进站失败";
            }

            return result;
        }

        /// <summary>
        /// 接受好友的火车
        /// </summary>
        /// <param name="train"></param>
        /// <param name="resultMessage"></param>
        /// <returns></returns>
        public bool Accept(TrainInfo train, out string resultMessage) {
            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "accept", 
                train.CityOrderId, train.TrainOwner.UserId, train.OId, 
                train.Type == TrainType.Sell ? train.Goods : train.Cash);

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data = (Dictionary<string, object>)content["data"];

            //获取数据是否成功的状态
            bool result = (string)data["result"] == "succ";
            if (result) {
                Dictionary<string, object> change = (Dictionary<string, object>)data["change"];

                int cash = Convert.ToInt32(change["cash"]);
                int goods = Convert.ToInt32(change["goods"]);

                if (cash > 0) {
                    resultMessage = String.Format("好友火车进站成功, 现金增加{0} 货物减少{1}", cash, goods);
                } else {
                    resultMessage = String.Format("好友火车进站成功, 现金减少{0} 货物增加{1}", cash, goods);
                }
            } else {
                resultMessage = "好友火车进站失败";
            }

            return result;
        }

        /// <summary>
        /// 获取火车定单
        /// </summary>
        /// <returns></returns>
        public List<TrainInfo> GetTrainOrders() {
            //初始化列表对象
            List<TrainInfo> oreders = new List<TrainInfo>();

            //获取AMF数据
            AMFMessage message = this.GetAMFMessage(this.Target, "getOrders");

            //解析数据
            Dictionary<string, object> content = (Dictionary<string, object>)message.Bodies[0].Content;
            Dictionary<string, object> data = (Dictionary<string, object>)content["data"];

            //获取数据是否成功的状态
            bool result = (string)data["result"] == "succ";
            if (result) {
                List<object> buyList = (List<object>)data["buylist"];
                List<object> sellList = (List<object>)data["selllist"];

                //遍历数据
                foreach (Dictionary<string, object> item in buyList) {
                    //初始化产品对象
                    TrainInfo info = new TrainInfo();

                    //赋值
                    info.Type = TrainType.Buy;
                    info.OName = (string)item["oname"];
                    info.OId = Convert.ToInt32((string)item["oid"]);
                    info.OTimes = Convert.ToInt32((string)item["otime"]);
                    info.Goods = Convert.ToInt32((string)item["goods"]);
                    info.Cash = Convert.ToInt32((string)item["cash"]);

                    oreders.Add(info);
                }

                //遍历数据
                foreach (Dictionary<string, object> item in sellList) {
                    //初始化产品对象
                    TrainInfo info = new TrainInfo();

                    //赋值
                    info.Type = TrainType.Sell;
                    info.OName = (string)item["oname"];
                    info.OId = Convert.ToInt32((string)item["oid"]);
                    info.OTimes = Convert.ToInt32((string)item["otime"]);
                    info.Goods = Convert.ToInt32((string)item["goods"]);
                    info.Cash = Convert.ToInt32((string)item["cash"]);

                    oreders.Add(info);
                }
            }

            return oreders;
        }
    }
}
